package org.jeecg.modules.villageCadreAssist.controller;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.constant.TemplateConstant;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.parse.impl.FileParseDelegate;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecg.modules.villageCadreAssist.entity.VcaFamily;
import org.jeecg.modules.villageCadreAssist.entity.VcaResident;
import org.jeecg.modules.villageCadreAssist.service.IVcaFamilyService;
import org.jeecg.modules.villageCadreAssist.service.IVcaResidentService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.villageCadreAssist.entity.VcaFileItem;
import org.jeecg.modules.villageCadreAssist.entity.VcaFileTemplate;
import org.jeecg.modules.villageCadreAssist.vo.VcaFileTemplatePage;
import org.jeecg.modules.villageCadreAssist.service.IVcaFileTemplateService;
import org.jeecg.modules.villageCadreAssist.service.IVcaFileItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: vca_file_template
 * @Author: jeecg-boot
 * @Date:   2022-02-23
 * @Version: V1.0
 */
@Api(tags="vca_file_template")
@RestController
@RequestMapping("/villageCadreAssist/vcaFileTemplate")
@Slf4j
public class VcaFileTemplateController {
	@Autowired
	private IVcaFileTemplateService vcaFileTemplateService;
	@Autowired
	private IVcaFileItemService vcaFileItemService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	 private ISysUserService sysUserService;
	@Autowired
	private IVcaResidentService vcaResidentService;
	@Autowired
	private IVcaFamilyService vcaFamilyService;
	@Autowired
	private FileParseDelegate fileParse;

	/**
	 * 分页列表查询
	 *
	 * @param vcaFileTemplate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "vca_file_template-分页列表查询")
	@ApiOperation(value="vca_file_template-分页列表查询", notes="vca_file_template-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(VcaFileTemplate vcaFileTemplate,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String name = vcaFileTemplate.getName();
		if(StringUtils.isNotEmpty(name)){//采用模糊查询，表数据不会太多，不影响性能
			vcaFileTemplate.setName("*"+name+"*");
			vcaFileTemplate.setRemark("*"+name+"*");
		}

		QueryWrapper<VcaFileTemplate> queryWrapper = QueryGenerator.initQueryWrapper(vcaFileTemplate, req.getParameterMap());
		Page<VcaFileTemplate> page = new Page<VcaFileTemplate>(pageNo, pageSize);
		IPage<VcaFileTemplate> pageList = vcaFileTemplateService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param vcaFileTemplatePage
	 * @return
	 */
	@AutoLog(value = "vca_file_template-添加")
	@ApiOperation(value="vca_file_template-添加", notes="vca_file_template-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("vcaFileTemplate:add")
	public Result<?> add(@RequestBody VcaFileTemplatePage vcaFileTemplatePage) {
		VcaFileTemplate vcaFileTemplate = new VcaFileTemplate();
		BeanUtils.copyProperties(vcaFileTemplatePage, vcaFileTemplate);
		vcaFileTemplateService.saveMain(vcaFileTemplate, vcaFileTemplatePage.getVcaFileItemList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param vcaFileTemplatePage
	 * @return
	 */
	@AutoLog(value = "vca_file_template-编辑")
	@ApiOperation(value="vca_file_template-编辑", notes="vca_file_template-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("vcaFileTemplate:edit")
	public Result<?> edit(@RequestBody VcaFileTemplatePage vcaFileTemplatePage) {
		VcaFileTemplate vcaFileTemplate = new VcaFileTemplate();
		BeanUtils.copyProperties(vcaFileTemplatePage, vcaFileTemplate);
		VcaFileTemplate vcaFileTemplateEntity = vcaFileTemplateService.getById(vcaFileTemplate.getId());
		if(vcaFileTemplateEntity==null) {
			return Result.error("未找到对应数据");
		}
		vcaFileTemplateService.updateMain(vcaFileTemplate, vcaFileTemplatePage.getVcaFileItemList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "vca_file_template-通过id删除")
	@ApiOperation(value="vca_file_template-通过id删除", notes="vca_file_template-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresPermissions("vcaFileTemplate:delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Integer id) {
		vcaFileTemplateService.delMain(id);
		return Result.OK("删除成功!");
	}

	 @AutoLog(value = "vca_file_template-获取模板数据")
	 @ApiOperation(value="vca_file_template-获取模板数据", notes="vca_file_template-获取模板数据")
	 @GetMapping(value = "/getHtmlData")
	 public Result<?> getHtmlData(Integer residentId) {
		 Map<String, Object> baseData = this.getBaseData(residentId);
		 return Result.OK(baseData);
	 }


	 @AutoLog(value = "vca_file_template-资料下载")
	 @ApiOperation(value="vca_file_template-资料下载", notes="vca_file_template-资料下载")
	 @GetMapping(value = "/downloadFile")
	 public void downloadFile(String url,Integer residentId,HttpServletResponse response) {
		 try {
			 response.setHeader("Content-Disposition", "attachment;fileName=file.docx");
			 response.setHeader("content-type","application/vnd.openxmlformats-officedocument.wordprocessingml.document");

			 fileParse.parse(url,getBaseData(residentId),response.getOutputStream());
		 } catch (FileNotFoundException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	 }

	 @AutoLog(value = "vca_file_template-模板下载")
	 @ApiOperation(value="vca_file_template-模板下载", notes="vca_file_template-模板下载")
	 @GetMapping(value = "/getHtml")
	 public void getHtml(String url,HttpServletResponse response) {
		 try {
			 response.setHeader("content-disposition", "attachment;fileName=file.docx");
			 response.setHeader("content-type","text/plain");
			 response.setCharacterEncoding("utf-8");
			 URL u = new URL(url);
			 HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			 //设置超时间为3秒
			 conn.setConnectTimeout(3 * 1000);
			 //得到输入流
			 InputStream inputStream = conn.getInputStream();
			 OutputStream outputStream = response.getOutputStream();
			 byte[] buffer = new byte[1024];
			 int n=0;
			 while ((n=inputStream.read(buffer))!=-1){
				 outputStream.write(buffer,0,n);
			 }
			 outputStream.flush();
			 conn.disconnect();
		 } catch (FileNotFoundException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	 }


	 @AutoLog(value = "vca_file_template-资料下载")
	 @ApiOperation(value="vca_file_template-资料下载", notes="vca_file_template-资料下载")
	 @GetMapping(value = "/downloadAllFile")
	 public void downloadAllFile(Integer templateId,Integer residentId,HttpServletResponse response) {
		 try {
			 response.setHeader("content-type","application/octet-stream");
			 List<VcaFileItem> itemList = vcaFileItemService.selectByMainId(templateId);

			 OutputStream outputStream = response.getOutputStream();
			 Map<String, Object> baseData = getBaseData(residentId);

			 LoginUser user = SecurityUtil.getLoginUser();
			 SysDepart depart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode, user.getOrgCode()));

			 if(itemList.size()>1){
				 VcaFileTemplate template = vcaFileTemplateService.getById(templateId);
				 response.setHeader("Content-Disposition", "attachment;fileName="+template.getName());
				 ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
				 for (VcaFileItem item : itemList) {
					 zipOutputStream.putNextEntry(new ZipEntry(parseFileName(item.getFileUrl(),depart)));
					 fileParse.parse(item.getFileUrl(),baseData,zipOutputStream);
				 }
				 zipOutputStream.close();
			 }else{
				 VcaFileItem item = itemList.get(0);
				 String fileUrl = item.getFileUrl();

				 response.setHeader("Content-Disposition", "attachment;fileName="+parseFileName(fileUrl,depart));
				 fileParse.parse(item.getFileUrl(),baseData,outputStream);
				 outputStream.close();
			 }
		 } catch (FileNotFoundException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	 }

	 private String parseFileName(String fileUrl,SysDepart depart){
		 String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1,fileUrl.lastIndexOf("_"))+fileUrl.substring(fileUrl.lastIndexOf("."));
		 fileName=fileName.replaceAll("\\$\\{village\\}",depart.getDepartName());
		 fileName=fileName.replaceAll("\\$\\{fullVillage\\}",depart.getDepartFullName());
		 return fileName;
	 }



	 //TODO 暂时查询所有数据，以后按需加载
	 private Map<String,Object> getBaseData(Integer residentId){
		 Map<String, Object> map = new HashMap<>();
		 LoginUser user = SecurityUtil.getLoginUser();
		 map.put(TemplateConstant.LOGIN_USER, user);
		 SysDepart loginDepart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode, user.getOrgCode()));
		 map.put(TemplateConstant.LOGIN_DEPART,loginDepart);
		 List<SysUser> userList = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgCode, user.getOrgCode()));
		 map.put(TemplateConstant.COLLEAGUE_LIST,userList);
		 map.put(TemplateConstant.NOW,DateUtils.formatDate(new Date(),"yyyy年MM月dd日"));

		 if(residentId!=null){
			 //本人信息
			 VcaResident resident = vcaResidentService.getById(residentId);
			 map.put(TemplateConstant.RESIDENT,resident);
//            Map<String, Object> map = BeanUtils.beanToMap(resident);
			 //家人人数
			 VcaFamily family = vcaFamilyService.getOne(new LambdaQueryWrapper<VcaFamily>().eq(VcaFamily::getFamilyCode, resident.getFamilyCode()));
			 map.put(TemplateConstant.FAMILY,family);
			 //所在村组信息
			 SysDepart depart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode, family.getAreaCode()));
			 map.put(TemplateConstant.DEPART,depart);
			 //家人人员
			 List<VcaResident> list = vcaResidentService.list(new LambdaQueryWrapper<VcaResident>().eq(VcaResident::getFamilyCode, resident.getFamilyCode()));
			 list = list.stream().filter(item->{
				 return !item.getId() .equals(resident.getId());
			 }).collect(Collectors.toList());
			 map.put(TemplateConstant.FAMILY_LIST,list);
		 }
		 return map;
	 }


	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "vca_file_template-批量删除")
	@ApiOperation(value="vca_file_template-批量删除", notes="vca_file_template-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@RequiresPermissions("vcaFileTemplate:deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.vcaFileTemplateService.delBatchMain(Arrays.asList(ids.split(","))
				.stream()
				.map(Integer::valueOf)
				.collect(Collectors.toList()));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "vca_file_template-通过id查询")
	@ApiOperation(value="vca_file_template-通过id查询", notes="vca_file_template-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		VcaFileTemplate vcaFileTemplate = vcaFileTemplateService.getById(id);
		if(vcaFileTemplate==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(vcaFileTemplate);

	}

	/**
	 * 通过id或code查询
	 *
	 * @return
	 */
	@AutoLog(value = "vca_file_item通过主表ID或code查询")
	@ApiOperation(value="vca_file_item主表ID或code查询", notes="vca_file_item-通主表ID或code查询")
	@GetMapping(value = "/queryVcaFileItemList")
	public Result<?> queryVcaFileItemList(VcaFileTemplate template) {
		List<VcaFileItem> vcaFileItemList = vcaFileItemService.selectByTemplate(template);

//		LoginUser user = SecurityUtil.getLoginUser();
//		SysDepart depart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode, user.getOrgCode()));
//		vcaFileItemList.forEach(item->{
//			String fileUrl = item.getFileUrl();
//			String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1,fileUrl.lastIndexOf("_"))+fileUrl.substring(fileUrl.lastIndexOf("."));
//			fileName=fileName.replaceAll("\\$\\{village\\}",depart.getDepartName());
//			fileName=fileName.replaceAll("\\$\\{fullVillage\\}",depart.getDepartName());
//			item.setFileName(fileName);
//		});
		return Result.OK(vcaFileItemList);
	}



    /**
    * 导出excel
    *
    * @param request
    * @param vcaFileTemplate
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("vcaFileTemplate:exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VcaFileTemplate vcaFileTemplate) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<VcaFileTemplate> queryWrapper = QueryGenerator.initQueryWrapper(vcaFileTemplate, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<VcaFileTemplate> queryList = vcaFileTemplateService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<VcaFileTemplate> vcaFileTemplateList = new ArrayList<VcaFileTemplate>();
      if(oConvertUtils.isEmpty(selections)) {
          vcaFileTemplateList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          vcaFileTemplateList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<VcaFileTemplatePage> pageList = new ArrayList<VcaFileTemplatePage>();
      for (VcaFileTemplate main : vcaFileTemplateList) {
          VcaFileTemplatePage vo = new VcaFileTemplatePage();
          BeanUtils.copyProperties(main, vo);
          List<VcaFileItem> vcaFileItemList = vcaFileItemService.selectByMainId(main.getId());
          vo.setVcaFileItemList(vcaFileItemList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "vca_file_template列表");
      mv.addObject(NormalExcelConstants.CLASS, VcaFileTemplatePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("vca_file_template数据", "导出人:"+sysUser.getRealname(), "vca_file_template"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@RequiresPermissions("vcaFileTemplate:importExcel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<VcaFileTemplatePage> list = ExcelImportUtil.importExcel(file.getInputStream(), VcaFileTemplatePage.class, params);
              for (VcaFileTemplatePage page : list) {
                  VcaFileTemplate po = new VcaFileTemplate();
                  BeanUtils.copyProperties(page, po);
                  vcaFileTemplateService.saveMain(po, page.getVcaFileItemList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }



}
